package com.guoqi.keepsign.mzt

import android.graphics.Color
import android.os.Bundle
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.View
import com.google.gson.Gson
import com.guoqi.keepsign.IPConfig.DEFAULT_TIMEOUT
import com.guoqi.keepsign.IPConfig.DEFUALT_USERAGENT
import com.guoqi.keepsign.R
import com.guoqi.keepsign.base.BaseFm
import com.guoqi.keepsign.base.CommonAdapter
import com.guoqi.keepsign.base.CommonBean
import kotlinx.android.synthetic.main.fm_common.*
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.select.Elements
import java.util.*


class MztFm : BaseFm(), SwipeRefreshLayout.OnRefreshListener {

    private lateinit var url: String
    private var showType = 1
    private var mList: ArrayList<CommonBean>? = null
    private var mPage: Int? = 1

    private var gm: GridLayoutManager? = null

    companion object {

        fun newInstance(ip: String, showType: Int): MztFm {
            val fragment = MztFm()
            val bundle = Bundle()
            bundle.putString("ip", ip)
            bundle.putInt("showType", showType)
            fragment.arguments = bundle
            return fragment
        }

    }

    override fun initLayout(): Int {
        return R.layout.fm_common
    }

    override fun initUI() {
        url = arguments?.getString("ip") ?: ""
        showType = arguments?.getInt("showType") ?: 2
        //activity?.showToast(url)
        mSwipeRefresh.setColorSchemeColors(Color.rgb(255, 64, 129))
        mSwipeRefresh.setOnRefreshListener(this)
        //lm = LinearLayoutManager(context)
        gm = GridLayoutManager(context, showType)
        mRvCommonList.layoutManager = gm
        mRvCommonList.setHasFixedSize(true)
        mList = ArrayList()

        loading.visibility = View.VISIBLE
        mRvCommonList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            var lastVisibleItem: Int? = 0
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem!! + 1 == mCommomAdapter?.itemCount) {
                    if (url.contains("/zhuanti/")) {
                        mCommomAdapter?.changeMoreStatus(mCommomAdapter?.NO_LOAD_MORE!!)
                    } else {
                        mCommomAdapter?.changeMoreStatus(mCommomAdapter?.LOAD_MORE!!)
                        mPage = mPage!! + 1
                        getData(mPage)
                    }

                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val layoutManager = recyclerView?.layoutManager as LinearLayoutManager
                //最后一个可见的ITEM
                lastVisibleItem = layoutManager.findLastVisibleItemPosition()
            }
        })
    }

    private fun getData(page: Int?) {
        Thread(Runnable {
            try {
                val doc: Document = Jsoup.connect(url + page)
                        .timeout(DEFAULT_TIMEOUT).userAgent(DEFUALT_USERAGENT).get()
                val imgSingle: Elements? = doc.getElementsByClass("lazy")

                imgSingle//?.map { it.select("img") }
                        ?.forEach {
                            mCommonBean = CommonBean(it.attr("alt"), it.attr("data-original"))
                            mList!!.add(mCommonBean!!)
                            Log.e(TAG, Gson().toJson(mCommonBean))
                        }
                activity?.runOnUiThread {
                    if (mPage != 1) {
                        if (url.contains("/zhuanti/")) {
                            mCommomAdapter?.changeMoreStatus(mCommomAdapter?.NO_LOAD_MORE!!)
                        } else {
                            mRvCommonList.adapter!!.notifyDataSetChanged()
                        }
                    } else {
                        mCommomAdapter = CommonAdapter(activity, mList)
                        mRvCommonList.adapter = mCommomAdapter
                    }
                    loading.visibility = View.GONE
                }
            } catch (e: Exception) {
                activity?.runOnUiThread {
                    loading.visibility = View.GONE
                    mCommomAdapter?.changeMoreStatus(mCommomAdapter?.NO_LOAD_MORE!!)
                }
            }
        }).start()
    }

    override fun onRefresh() {
        mSwipeRefresh.isRefreshing = false
        getData(mPage)
    }

    override fun loadData() {
        if (mList!!.isEmpty())
            getData(mPage)
    }

}